package cn.hdr.train.copy;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: hdr
 * @date: 2020-09-14 16:21
 */
public class OtherTest {
    public static void main(String[] args) throws Exception{

        String rootPath = System.getProperty("user.dir");

        //4k
        byte[] byte_4 = new byte[1024 * 4];
        testFile(byte_4,rootPath + File.separator + "testFile4");
        testFileChannel(byte_4,rootPath + File.separator + "testFileChannel4");
        testMapMemory(byte_4,rootPath + File.separator + "testMapMemory4");

        //128k
        byte[] byte_128 = new byte[1024 * 128];
        testFile(byte_128,rootPath + File.separator + "testFile128");
        testFileChannel(byte_128,rootPath + File.separator + "testFileChannel128");
        testMapMemory(byte_128,rootPath + File.separator + "testMapMemory128");

        //1M
        byte[] byte_1M = new byte[1024 * 1024 * 1];
        testFile(byte_1M,rootPath + File.separator + "testFile1M");
        testFileChannel(byte_1M,rootPath + File.separator + "testFileChannel1M");
        testMapMemory(byte_1M,rootPath + File.separator + "testMapMemory1M");
    }


    public static void testFile(byte[] bytes,String fileName) throws Exception{
        long start = System.currentTimeMillis();
        RandomAccessFile randomFile = new RandomAccessFile(new File(fileName), "rw");
        for (int i = 0; i < 100; i++) {
            randomFile.write(bytes);
        }
        randomFile.close();

        long cast = System.currentTimeMillis() - start;
        System.out.println("File11\t"+bytes.length+"\t" + cast);
    }

    public static void testFileChannel(byte[] bytes,String fileName) throws Exception{
        long start = System.currentTimeMillis();
        FileChannel channel = new RandomAccessFile(new File(fileName), "rw").getChannel();
        ByteBuffer wrap = ByteBuffer.wrap(bytes);
        for (int i = 0; i < 100; i++) {
            channel.write(wrap,i * bytes.length);
        }
        channel.close();

        long cast = System.currentTimeMillis() - start;
        System.out.println("channel\t"+bytes.length+"\t" + cast);
    }

    public static void testMapMemory(byte[] bytes,String fileName) throws Exception{
        long start = System.currentTimeMillis();
        FileChannel channel = new RandomAccessFile(new File(fileName ), "rw").getChannel();
        MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, bytes.length * 100);
        ByteBuffer wrap = ByteBuffer.wrap(bytes);
        for (int i = 0; i < 100; i++) {
            map.put(wrap);
        }
        channel.close();
        long cast = System.currentTimeMillis() - start;
        System.out.println("MapByt\t"+bytes.length+"\t" + cast);
    }
}